/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.mushroom.website.security;

import cz.muni.fi.pa165.mushroom.website.dto.GathererDto;
import cz.muni.fi.pa165.mushroom.website.services.GathererService;
import cz.muni.fi.pa165.mushroom.website.servicesImpl.GathererServiceImpl;
import java.util.Arrays;
import java.util.HashSet;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;

/**
 * Web realm for shiro security
 * 
 * @author Roman Jakubco <roman.jakubco@gmail.com>
 */
public class WebRealm extends AuthorizingRealm {

   @SpringBean
    protected GathererServiceImpl gathererServiceImpl;
   
    private static final AuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(new HashSet(Arrays.asList("ROLE_USER","ROLE_REGISTERED")));

    public GathererServiceImpl getGathererServiceImpl() {
        return gathererServiceImpl;
    }

    public void setGathererServiceImpl(GathererServiceImpl gathererServiceImpl) {
        this.gathererServiceImpl = gathererServiceImpl;
    }

    

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {      
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String userName = usernamePasswordToken.getUsername();        
        SimpleAuthenticationInfo info = null;        
        for (GathererDto g : gathererServiceImpl.listGatherers()) {          
            if (g.getUsername().equals(userName)) {               
                info = new SimpleAuthenticationInfo(userName, g.getPassword(), new SimpleByteSource(g.getSalt()), this.getName());
                break;
            }
        }

        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        
        String userName = (String) principals.getPrimaryPrincipal();
        AuthorizationInfo info = null;
        for (GathererDto g : gathererServiceImpl.listGatherers()) {
            if (g.getUsername().equals(userName)) {
                info = authorizationInfo;
                break;
            }
        }
        return info;
    }
    
}
